/*
Script Name: Dynamic Keyword Insertion Tool
Author: Tim Spinks
Website: http://www.ninthlink.com
Requires: jQuery
Version: 0.2.2

See Wiki for details: https://code.google.com/p/dynamic-keyword-insertion/wiki/WikiDKI
*/

jQuery(function($){
	
	/* * * * * * * * *
	Function converts all URL query parameters into object
	* * * * * * * * */
	function urlParams() {
		// get query string after '?' and split into array around '&'...
		var pairs = location.search.slice(1).split('&');
		var result = {}; // new object
		pairs.forEach( function( pair ) {
			// split sub arrays into key/value pair by '='...
			pair = pair.split( '=' );
			// split result into array aound space/%20 with key value pairs
			// regex ensures accidental {keyword} dki from Google AdWords doesn't get in the mix
			result[pair[0]] = ! /(\{[a-zA-Z0-9\s%20\:]{0,}\})/.test( pair[1] ) ? decodeURIComponent( pair[1] || '' ).match(/[^\s]+/gi) : '';
		});
		// convert to object and return
		return JSON.parse( JSON.stringify( result ) );
	}

	// store params object in var 'p'
	var p = urlParams();
	console.log(p); // debug

	// if custom over-write object 'dki' exists, set key interval 'i' (so we don't accidentally lose anything)
	if ( typeof( dki ) != "undefined" && dki !== null ) {
		var i = Object.keys( dki ).length,
			dki_exists = true;
	}
	else {
		i = 0,
		dki_exists = false;
	}

	// new empty object to store loop results
	var _dki = new Object();

	// if standard elements with '.dki' class exist, lets add those to our new _dki object
	if ( $('.dki').length ) {
		$('.dki').each(function(){
			_dki[i]				= new Object();
			_dki[i].elem		= $(this);
			_dki[i].trigger		= $(this).attr("dkiTrigger");
			_dki[i].group		= $(this).attr("dkiGroup");
			i++;
		});
	}

	// 'i' is no longer needed so we delete it just in case
	delete i;

	// if custom over-writes exist, merge two objects into one, with over-writes taking precedence
	if ( dki_exists ) {
		$.extend( _dki, dki );
	}

	/* * * * * * * * *
	Now that we have a complete object of all elements on page requiring a rewrite
	we loop through the object to find the necessary keyword trigger/value pairs
	and replace the inner html of each element as necessary. HTML values supported.
	* * * * * * * * */
	$.each( _dki, function( k, v ) {

		__dki				= new Object();
		__dki.this			= $( v.elem );
		__dki.trigger		= ( typeof( v.trigger ) != "undefined" && v.trigger !== null ) ? v.trigger : 'kw';
		__dki.group			= eval( v.group );

		// iterate through GROUP and compare against keywords in URL params
		$.each( 
			__dki.group,
			function( key, value )
			{

				// if GROUP trigger exists in URL params...
				if ( typeof( p[ __dki.trigger ] ) != "undefined" && p[ __dki.trigger ] !== null ) {

					// iterate through URL param values to compare against current GROUP value
					for ( var i = 0; i < p[ __dki.trigger ].length; i++ ) {

						// if URL param value matches current GROUP value...
						if ( p[ __dki.trigger ][ i ] === key ) {

							// set img source or element inner html
							if ( __dki.this.is('img') ) {
								__dki.this.attr( 'src', value );
							}
							else {
								__dki.this.html( value );
							}

							// break out of FOR loop on success to preserve heirarchy of GROUP values
							return false;
						
						}
					
					}

				}

			}

		);

		// remove variable because it will be rebuilt on next iteration and we do not want ghost values appearing
		delete __dki;

	});
	
	console.log(_dki); // debug

});